package cn.shuto.liferay.plugin.chart.service.util;

import javax.portlet.ActionRequest;

import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringUtil;

public class JsonUtil {
	public static String getTemplateParam(ActionRequest request){
		String templateParam = "";
		String chart_legend_data_indexes_param = ParamUtil.getString(request, "template_script_param_fields_indexes");
		
		String[] chart_legend_data_indexes = StringUtil.split(chart_legend_data_indexes_param, ",");
		if(chart_legend_data_indexes.length>0){
			JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
			for (String chart_legend_data_index : chart_legend_data_indexes) {
				JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
				jsonObject.put("paramtag",  ParamUtil.getString(request, "paramtag"+chart_legend_data_index));
				jsonObject.put("paramname",  ParamUtil.getString(request, "paramname"+chart_legend_data_index));
				jsonObject.put("paramhelp",  ParamUtil.getString(request, "paramhelp"+chart_legend_data_index));
				jsonObject.put("isdbparam",  ParamUtil.getBoolean(request, "isdbparam"+chart_legend_data_index));
				jsonObject.put("paramtype",  ParamUtil.getString(request, "paramtype"+chart_legend_data_index));
				jsonArray.put(jsonObject);
			}
			templateParam=jsonArray.toString();
		}
		return templateParam;
	}
	
	public static String getTemplateParamValue(ActionRequest request){
		JSONObject paramvalue = JSONFactoryUtil.createJSONObject();
		String templateParam = ParamUtil.getString(request, "templateParam");
		JSONArray jsonArray;
		try {
			jsonArray = JSONFactoryUtil.createJSONArray(templateParam);
			if(jsonArray!=null&&jsonArray.length()>0){
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					String paramTag = jsonObject.getString("paramtag");
					if("boolean".equals(jsonObject.getString("paramtype"))){
						paramvalue.put(paramTag, ParamUtil.getBoolean(request, paramTag));
					}else if("number".equals(jsonObject.getString("paramtype"))){
						paramvalue.put(paramTag, ParamUtil.getDouble(request, paramTag));
					}else{
						paramvalue.put(paramTag, ParamUtil.getString(request, paramTag));
					}
					
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return paramvalue.toString();
	}
	public static JSONObject analysisTemplateParamValue(String templateParamJson) throws JSONException{
		return JSONFactoryUtil.createJSONObject(templateParamJson);
	}
	public static JSONArray analysisTemplateParam(String templateParamJson) throws JSONException{
		JSONArray jsonArray = JSONFactoryUtil.createJSONArray(templateParamJson);
		return jsonArray;
	}
	
}
